/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl;

import com.je.bpm.engine.ActivitiException;
import com.je.bpm.engine.impl.context.Context;
import com.je.bpm.engine.impl.interceptor.Command;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.interceptor.CommandExecutor;
import com.je.bpm.engine.query.NativeQuery;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Abstract superclass for all native query types.
 * 所有sql查询的抽象实现父类
 */
public abstract class AbstractNativeQuery<T extends NativeQuery<?, ?>, U> implements Command<Object>, NativeQuery<T, U>, Serializable {

    private static final long serialVersionUID = 1L;

    private static enum ResultType {
        LIST, LIST_PAGE, SINGLE_RESULT, COUNT
    }

    protected transient CommandExecutor commandExecutor;
    protected transient CommandContext commandContext;

    protected int maxResults = Integer.MAX_VALUE;
    protected int firstResult;
    protected ResultType resultType;

    private Map<String, Object> parameters = new HashMap<String, Object>();
    private String sqlStatement;

    protected AbstractNativeQuery(CommandExecutor commandExecutor) {
        this.commandExecutor = commandExecutor;
    }

    public AbstractNativeQuery(CommandContext commandContext) {
        this.commandContext = commandContext;
    }

    public AbstractNativeQuery<T, U> setCommandExecutor(CommandExecutor commandExecutor) {
        this.commandExecutor = commandExecutor;
        return this;
    }

    @SuppressWarnings("unchecked")
    @Override
    public T sql(String sqlStatement) {
        this.sqlStatement = sqlStatement;
        return (T) this;
    }

    @SuppressWarnings("unchecked")
    @Override
    public T parameter(String name, Object value) {
        parameters.put(name, value);
        return (T) this;
    }

    @SuppressWarnings("unchecked")
    @Override
    public U singleResult() {
        this.resultType = ResultType.SINGLE_RESULT;
        if (commandExecutor != null) {
            return (U) commandExecutor.execute(this);
        }
        return executeSingleResult(Context.getCommandContext());
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<U> list() {
        this.resultType = ResultType.LIST;
        if (commandExecutor != null) {
            return (List<U>) commandExecutor.execute(this);
        }
        return executeList(Context.getCommandContext(), getParameterMap(), 0, Integer.MAX_VALUE);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<U> listPage(int firstResult, int maxResults) {
        this.firstResult = firstResult;
        this.maxResults = maxResults;
        this.resultType = ResultType.LIST_PAGE;
        if (commandExecutor != null) {
            return (List<U>) commandExecutor.execute(this);
        }
        return executeList(Context.getCommandContext(), getParameterMap(), firstResult, maxResults);
    }

    @Override
    public long count() {
        this.resultType = ResultType.COUNT;
        if (commandExecutor != null) {
            return (Long) commandExecutor.execute(this);
        }
        return executeCount(Context.getCommandContext(), getParameterMap());
    }

    @Override
    public Object execute(CommandContext commandContext) {
        if (resultType == ResultType.LIST) {
            return executeList(commandContext, getParameterMap(), 0, Integer.MAX_VALUE);
        } else if (resultType == ResultType.LIST_PAGE) {
            Map<String, Object> parameterMap = getParameterMap();
            parameterMap.put("resultType", "LIST_PAGE");
            parameterMap.put("firstResult", firstResult);
            parameterMap.put("maxResults", maxResults);
            if (StringUtils.isNotBlank(ObjectUtils.toString(parameterMap.get("orderBy")))) {
                parameterMap.put("orderByColumns", "RES." + parameterMap.get("orderBy"));
            } else {
                parameterMap.put("orderByColumns", "RES.ID_ asc");
            }

            int firstRow = firstResult + 1;
            parameterMap.put("firstRow", firstRow);
            int lastRow = 0;
            if (maxResults == Integer.MAX_VALUE) {
                lastRow = maxResults;
            } else {
                lastRow = firstResult + maxResults + 1;
            }
            parameterMap.put("lastRow", lastRow);
            return executeList(commandContext, parameterMap, firstResult, maxResults);
        } else if (resultType == ResultType.SINGLE_RESULT) {
            return executeSingleResult(commandContext);
        } else {
            return executeCount(commandContext, getParameterMap());
        }
    }

    public abstract long executeCount(CommandContext commandContext, Map<String, Object> parameterMap);

    /**
     * Executes the actual query to retrieve the list of results.
     *
     * @param maxResults
     * @param firstResult
     * @param page        used if the results must be paged. If null, no paging will be applied.
     */
    public abstract List<U> executeList(CommandContext commandContext, Map<String, Object> parameterMap, int firstResult, int maxResults);

    public U executeSingleResult(CommandContext commandContext) {
        List<U> results = executeList(commandContext, getParameterMap(), 0, Integer.MAX_VALUE);
        if (results.size() == 1) {
            return results.get(0);
        } else if (results.size() > 1) {
            throw new ActivitiException("Query return " + results.size() + " results instead of max 1");
        }
        return null;
    }

    private Map<String, Object> getParameterMap() {
        HashMap<String, Object> parameterMap = new HashMap<String, Object>();
        parameterMap.put("sql", sqlStatement);
        parameterMap.putAll(parameters);
        return parameterMap;
    }

    public Map<String, Object> getParameters() {
        return parameters;
    }

}
